<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>实时日志</title>
    <script src="./js/sockjs.min.js"></script>
    <script src="./js/stomp.js"></script>
    <script src="./js/jquery-3.1.1.js"></script>
</head>
<body>
<noscript><h2 style="color:#ff0000">抱歉,您的浏览器不支持该功能!</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <textarea id="response"></textarea>
    </div>
</div>
</body>
<script type="text/javascript">
    var ws;

    function setConnected(connected){
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        // document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    }

    function connect(){
        ws = new WebSocket('ws://localhost:8081/webSocket');
        ws.onopen = WSonOpen;
        ws.onmessage = WSonMessage;
        ws.onclose = WSonClose;
        ws.onerror = WSonError;
    }

    function WSonOpen() {
        var message = {
            Content:'成功连接'
        }
        setConnected(true);
        showResponse(message)
    };

    function WSonMessage(event) {
        var message = {
            Content:event.data
        }
        showResponse(message)
    };

    function WSonClose() {
        var message = {
            Content:'连接断开'
        }
        showResponse(message)
    };

    function WSonError() {
        var message = {
            Content:'连接错误！'
        }
        showResponse(message)
    };

    function disconnect(){
        ws.close()
        setConnected(false);
    }

    function sendMessage(){
        ws.send(JSON.stringify({'Content':Content}))
    }

    function showResponse(message){
         var response = $("#response").val();
         $("#response").val(response+message.Content+'\n');
         // 一直滚到到最底部，会造成显示延迟
        var textarea = document.getElementById("response");
        textarea.scrollTop = textarea.scrollHeight;
    }
</script>
</html>